(function() {

	GameShake = function(rpc) {
		this.rpc = rpc;
		this.SHAKE_TRESHOLD = 500;
		this.watch_id = null;
		this.options = {
			frequency : 200
		};
		this.last_update = 0;
		this.last_x = 0;
		this.last_y = 0;
		this.last_z = 0;
		this.is_background = false;
	};

	GameShake.prototype = {
		start : function(is_background) {
			this.is_background = is_background;
			this.watchID = navigator.accelerometer.watchAcceleration(this.sensor_changed.bind(this),
					this.on_error.bind(this), this.options);
		},
		
		show : function() {
			$('#screen_game_shake').show();
		},
		hide : function() {
			$('#screen_game_shake').hide();
		},
		
		sensor_changed : function(a) {

			var diff_time, speed;
			// Idea:
			// http://stackoverflow.com/questions/5271448/how-to-detect-shake-event-with-android
			//if ((a.timestamp - this.last_update) > 100) {
			diff_time = a.timestamp - this.last_update;
			this.last_update = a.timestamp;
			
			speed = Math.abs(a.x + a.y + a.z - this.last_x - this.last_y - this.last_z) / diff_time * 10000;
			
			//this.debug(a, speed);
			
			if(speed > this.SHAKE_TRESHOLD) {
				this.rpc.send_shake_event();
				 navigator.notification.vibrate(500);
			}
			//}
			this.last_x = a.x;
			this.last_y = a.y;
			this.last_z = a.z;
		},
		debug : function(a, speed) {
			var element = document.getElementById('debug');
	        element.innerHTML = 'Acceleration X: ' + a.x + '<br />' +
            'Acceleration Y: ' + a.y + '<br />' +
            'Acceleration Z: ' + a.z + '<br />' +
            'Timestamp: '      + a.timestamp + '<br />' + 
            'Speed: '      + speed + '<br />';
		},
		
		stop : function() {
			if (this.watch_id) {
				navigator.accelerometer.clearWatch(this.watch_id);
				this.watch_id = null;
			}
		},
		
		on_error: function() {
			console.log("game shake - error!");
			this.stop();
			this.start();
			
		}
	};

})();